<?php

namespace app\admin\controller\xiluedu;

use app\common\controller\Backend;
use app\common\model\xiluedu\UserVip;
use app\common\model\xiluedu\Vip;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    /**
     * User模型对象
     * @var \app\admin\model\xiluedu\User
     */
    protected $model = null;
    protected $relationSearch = true;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\xiluedu\User;
        $this->view->assign("statusList", $this->model->getStatusList());
        // Vip::column('id,name')
        $this->assignconfig("vipConfig", Vip::column('id,name'));
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        
        $this->model = new \app\admin\model\xiluedu\User;

        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with(['vip' => function ($query) {
                $query->withField(['vip_id']);
            }])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
      
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }



    /**
     * 我的课程
     */
    public function course()
    {
   
        $this->relationSearch = false;
        $this->request->filter(['strip_tags']);
        $this->model = new \app\common\model\xiluedu\UserCourse();
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['course2'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 日志
     */
    public function moneylog()
    {
        $this->relationSearch = false;
        $this->request->filter(['strip_tags']);
        $this->model = new \app\common\model\MoneyLog();
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 设置vip
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function setvip($ids = null)
    {

        $row = UserVip::get(['user_id' => $ids]);


        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {

            $this->view->assign('viplist', array_merge([0 => '无'], Vip::column('id,name')));
            if (!$row) {
                $row['vip_id'] = 0;
            }
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        Db::startTrans();
        try {
            #更新会员卡时间
            $user_vip = UserVip::where('user_id', $ids)->find();
            if (!$user_vip) {
                $vip = Vip::get($params['vip_id']);
                if ($vip) {
                    if ($vip->unit == '3') {
                        $unit = 'year';
                    } else if ($vip->unit == '2') {
                        $unit = 'month';
                    } else {
                        $unit = 'day';
                    }
                    $expire_time = strtotime(date('Y-m-d', strtotime($vip->expire_in . ' ' . $unit)));
                    $user_vip_ret = [
                        'user_id'   =>  $ids,
                        'vip_id'    =>  $params['vip_id'],
                        'expire_time' => $expire_time
                    ];
                    UserVip::create($user_vip_ret);
                }
            } else {
                if ($params['vip_id'] <= 0) {
                    UserVip::where('user_id', $ids)->delete();
                }
            }
            Db::commit();
        } catch (ValidateException | PDOException | \Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success();
    }
}
